import unittest
import os

from lxml import etree


def printToFile(fileName='爬取内容.txt', content='') -> None:
    with open(fileName, mode='a', encoding='utf-8') as f:
        f.write(content)


class XPathTest(unittest.TestCase):
    def setUp(self) -> None:
        # res = requests.get("https://blog.csdn.net/qq_38289451", headers="")
        # self.rootElement = etree.HTML(res.text)
        pass

    # /  从当前节点选择直接子节点
    # // 从当前节点选择子孙节点
    # . 选取当前节点
    # ..  选取当前节点的父节点
    # @  选取属性
    def test_xpath(self):
        rootElement = etree.parse('test.html', etree.HTMLParser())
        # elements = rootElement.xpath('//div//a/../@class')
        elements = rootElement.xpath('//div//a')
        for e in elements:
            elementTxt = etree.tostring(e, encoding='utf-8')
            print(f"{type(e)} -> 元素标签原内容：{elementTxt}")

        contentList = rootElement.xpath('//div//a/text()')
        c = ''
        for content in contentList:
            c = c + content + '\n'
        str = input()
        c = c + str
        printToFile(content=c)


if __name__ == '__main__':
    # unittest.main(verbosity=2)
    x = XPathTest()
    x.test_xpath()
